<template>
    <div class="planList-index yuan-container">
        <div class="filter-panel">
            <span class="planList-title">
                {{planSimulation.planName}}({{planSimulation.planSerial}})
            </span>
            <div class="filter-list">
                <span class="filter-tips ">需求量：
                    <span class="font-bignum c-primary">{{planSimulation.xuqiu}}</span>
                    <span>kg</span>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips ">投料量：
                    <span class="font-bignum c-primary">{{(pageData.touliao  )|| '--' }}</span>
                    <span>kg</span>
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">剩余需求量:
                    <span class="font-bignum c-warning">{{(pageData.shenchan  )|| '--'}}</span>
                    <span>kg</span>
                </span>
            </div>
        </div>
        <div class="planList-top filter-panel">
            <div class="filter-list">
                <span class="filter-tips">预计完成时间：
                    <span class="mast-ico"></span>
                    <a-date-picker class="yuan-form-input" placeholder="预计完成时间" v-model="pageData.finishTime"
                        valueFormat="YYYY-MM-DD" />
                </span>
            </div>
            <div class="filter-list">
                <span class="filter-tips">提取物状态：<span class="mast-ico"></span></span>

                <a-select v-model="pageData.jgfState" allowClear placeholder="提取物状态">
                    <a-select-option value="1">混一</a-select-option>
                    <a-select-option value="2">混二</a-select-option>
                </a-select>
            </div>
        </div>

        <div style="border-bottom:solid 1px #999;margin-bottom:20px"></div>
        <div style="font-size:16px;font-weight:bold;margin-bottom:10px">
            辅料
        </div>
        <div class="filter-panel">
            <div v-for="(item,idx) in accSelList">
                <div class="filter-list">
                    <span class="filter-tips">投入辅料：</span>
                    <a-select v-model="accSelList[idx].accId" allowClear placeholder="请选择辅料">
                        <a-select-option :value="item.id" v-for="item in accList" :key="item.id">{{item.materialName}}</a-select-option>
                    </a-select>
                </div>
                <div class="filter-list">
                    <span class="filter-tips">投入数量：</span>
                    <a-input class="filter-input" suffix="kg" v-model="accSelList[idx].inputNum"></a-input>
                </div>
                <div class="filter-list" v-if="idx===0">
                    <a-button type="primary" @click="addAcc">新增</a-button>
                </div>
                <div class="filter-list" v-if="idx!==0">
                    <a-button type="danger" @click="removeAcc(idx)">删除</a-button>
                </div>
            </div>
        </div>

        <div style="font-size:16px;font-weight:bold;margin-bottom:20px">
            <span>
                {{planSimulation.materialName}}{{planSimulation.materialType}} 库存现状
            </span>
        </div>
        <div style="margin-bottom:20px">
            <span>是否使用现有库存批次：</span>
            <a-radio-group v-model="pageData.useStore" @change="useStoreChange">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
            </a-radio-group>
        </div>
        <template v-if="pageData.useStore===true">
            <div class="filter-panel">
                <div class="filter-list">
                    <span>批号：</span>
                    <a-input-search allowClear v-model="pageParams.batch" placeholder="请输入关键字" @search="resetList" />
                </div>
                <div class="filter-list">
                    <span>可供销售天数：</span>
                    <span class="filter-range">
                        <a-input v-model="pageParams.sellDayStart"></a-input>
                        <span class="filter-tips">~</span>
                        <a-input v-model="pageParams.sellDayEnd"></a-input>
                        <span class="filter-tips">天</span>
                    </span>
                </div>
                <div class="filter-list">
                    <span>质量状态：</span>
                    <a-select v-model="pageParams.qualityState" @change="resetList" allowClear placeholder="请选择质量状态">
                        <a-select-option value="1">合格</a-select-option>
                        <a-select-option value="2">不合格</a-select-option>
                    </a-select>
                </div>
                <div class="filter-list">
                    <span>有效期：</span>
                    <a-range-picker :mode="['month','month']" :open="monthPickShow" @panelChange="handlePanelChange"
                        v-model="billMonth" @openChange="handleOpenChange" :placeholder="['开始日期','结束日期']"
                        :format="['YYYY-MM','YYYY-MM']" />
                </div>
                <div class="filter-list">
                    <a-button type="primary" @click="getList" class="filter-list">搜索</a-button>
                </div>
            </div>
            <div class="table">
                <a-radio-group v-model="tableSelect" @change="pageListSelectChange" style="width:100%">
                    <a-table bordered :rowKey="(row)=>row.id" :data-source="pageList" :columns="packageColumns"
                        :pagination="false" :loading="loading">
                        <template slot="select" slot-scope="text, record, index">
                            <a-radio :value="index"></a-radio>
                        </template>
                        <template slot="inputNumber" slot-scope="text, record, index">
                            <span v-if="!pageList[index].isSelect">--</span>
                            <a-input type="number" style="width:100px" placeholder="请输入数量"
                                v-model="pageList[index]['inputNumber']" @input="inputNumChange" v-else />

                        </template>
                        <template slot="qualityState" slot-scope="text, record, index">
                            <span>{{record.qualityState === "1" ? "合格" : "待检"}}</span>
                        </template>
                    </a-table>
                </a-radio-group>
            </div>
        </template>

    </div>
</template>
<script lang="ts">
import warningApi from "@/api/warningApi";
import { toDecimalNoZero } from "@/utils";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";

@Component({
    name: "dom",
    components: {},
})
export default class index extends Vue {
    @Prop({ default: "" }) planSimulation!: any;
    @Prop({ default: "" }) alarmData!: any;
    @Watch("planSimulation")
    visibleChange() {
        if (this.planSimulation) {
            this.pageData = {
                touliao: "",
                shenchan: "",
            };
            this.getList();
        }
    }
    // 计划表格
    packageColumns = [
        {
            align: "center",
            dataIndex: "select",
            key: "select",
            title: "",
            scopedSlots: { customRender: "select" },
        },
        {
            align: "center",
            dataIndex: "batch",
            key: "batch",
            title: "批号",
        },
        {
            align: "center",
            dataIndex: "scTime",
            key: "scTime",
            title: "生产日期",
        },
        {
            align: "center",
            dataIndex: "validTime",
            key: "validTime",
            title: "有效期至",
        },
        {
            align: "center",
            dataIndex: "qualityState1",
            key: "qualityState1",
            title: "复验期",
        },
        {
            align: "center",
            dataIndex: "surplus",
            key: "surplus",
            title: "库存数量",
            customRender: (text: string, record: any, index: number) => toDecimalNoZero(record.surplus, 2),
        },
        {
            align: "center",
            dataIndex: "qualityState3",
            key: "qualityState3",
            title: "可销售天数",
        },
        {
            align: "center",
            dataIndex: "qualityState",
            key: "qualityState",
            title: "质量状态",
            scopedSlots: { customRender: "qualityState" },
        },
        {
            align: "center",
            dataIndex: "qualityState123",
            key: "qualityState123",
            title: "生产状态",
        },
        {
            align: "center",
            dataIndex: "inputNumber",
            key: "inputNumber",
            title: "投料量（kg）",
            scopedSlots: { customRender: "inputNumber" },
        },
    ];
    loading = false;
    pageParams: any = {
        batch: "",
        qualityState: undefined,
        sellDayStart: "",
        sellDayEnd: "",
        startTime: "",
        endTime: "",
    };
    pagination = {
        pageSize: 999,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    pageList: any[] = [];
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    async getList() {
        this.tableSelect = "";
        this.pageList = [];
        try {
            this.loading = true;
            const res = await warningApi.materialStockList({
                ...this.pageParams,
                pageSize: this.pagination.pageSize,
                page: this.pagination.current,
                materialName: this.planSimulation.materialName,
                materialType: this.planSimulation.materialType,
            });
            // 如果没有库存 直接下一步
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.records || [];
            if (this.pageList.length === 0) {
                this.pageData.touliao = 0;
                this.pageData.shenchan = toDecimalNoZero(this.planSimulation.xuqiu);
                this.$emit("inputNumChange", {
                    id: this.planSimulation.materialId,
                    need: this.planSimulation.xuqiu,
                    nextPlan: ["提取计划", "饮片计划"],
                });
            }
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    useStoreChange() {
        if (this.pageData.useStore) {
            this.pageListSelectChange();
        } else {
            this.pageData.touliao = 0;
            this.pageData.shenchan = toDecimalNoZero(this.planSimulation.xuqiu);
            this.$emit("inputNumChange", {
                id: this.planSimulation.materialId,
                need: this.planSimulation.xuqiu,
                nextPlan: ["提取计划", "饮片计划"],
            });
        }
    }
    billMonth = [];
    monthPickShow = false;
    handlePanelChange(value, mode) {
        if (mode[1] === "date") {
            const arr = value.map((item) => item.format("YYYY-MM"));
            this.billMonth = arr;
            this.pageParams.startTime = arr[0];
            this.pageParams.endTime = arr[1];
            this.resetList();
            this.monthPickShow = false;
        }
    }
    handleOpenChange(status) {
        if (status) {
            this.monthPickShow = true;
        } else {
            this.monthPickShow = false;
        }
    }

    tableSelect = "";
    pageListSelectChange() {
        const pageList = [...this.pageList];
        let store = pageList[this.tableSelect].surplus;
        //如果选择的库存小于需求量 提示
        if (store < this.planSimulation.xuqiu) {
            this.$message.error("该批次库存量无法满足投料需求量，请选择库存量充足批次或重新生产");
            this.tableSelect = "";
            return;
        }

        const type = pageList[this.tableSelect].isSelect;
        pageList.map((item) => {
            item.isSelect = false;
        });
        let inNum = 0;
        if (!type) {
            pageList[this.tableSelect].isSelect = true;

            if (store > this.planSimulation.xuqiu) {
                inNum = this.planSimulation.xuqiu;
            } else {
                inNum = store;
            }

            pageList[this.tableSelect].inputNumber = inNum;
        }
        this.pageList = pageList;
        this.inputNumChange();
    }
    mounted() {
        this.getList();
        this.getAccList();
    }
    pageData: any = {
        useStore: true,
        touliao: "",
        shenchan: "",
    };
    simulationTimer: number | null = null;
    inputNumChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            let total = Number(this.pageList[this.tableSelect]["inputNumber"]) || 0;
            if (total > this.pageList[this.tableSelect].surplus) {
                this.$message.error("投料数量不能大于库存量");
                return;
            }
            if (total > this.planSimulation.xuqiu) {
                this.$message.error("投料数量不能大于需求量");
                return;
            }
            this.pageData.touliao = toDecimalNoZero(total);
            this.pageData.shenchan = toDecimalNoZero(this.planSimulation.xuqiu - total);
            this.$emit("inputNumChange", {
                id: this.planSimulation.materialId,
                need: this.planSimulation.xuqiu - total,
                nextPlan: ["提取计划", "饮片计划"],
            });
        }, 500);
    }
    accSelList: any[] = [{}];
    accList: any[] = [];
    async getAccList() {
        this.accList = [];
        try {
            this.loading = true;
            const res = await warningApi.materialStockList({
                pageSize: 999,
                page: 1,
                materialType: "辅料",
            });
            this.accList = res.data?.records || [];
        } finally {
            this.loading = false;
        }
    }
    addAcc() {
        this.accSelList.push({});
    }
    removeAcc(idx) {
        this.accSelList.splice(idx, 1);
    }

    getPageInfo() {
        if (!this.pageData.finishTime) {
            this.$message.error("请选择制剂计划预计完成时间");
            return false;
        }
        const processPlanInputList: any[] = [];
        let total = 0;
        if (this.pageData.useStore === false) {
            const item = this.pageList[0];
            // 投料
            processPlanInputList.push({
                isPro: this.pageData.useStore,
                stockId: "",
                batch: "",
                inputNum: 0,
                materialName: item.materialName,
                materialType: item.materialType,
                materialId: item.materialId,
            });
        } else {
            const item = this.pageList[this.tableSelect];
            if (!item) {
                this.$message.error("制剂计划还没有选择投料");
                return false;
            }
            total = Number(item["inputNumber"]) || 0;
            if (total > this.planSimulation.xuqiu) {
                this.$message.error("包装计划投料数量不能大于需求量");
                return false;
            }
            if (total > item.surplus) {
                this.$message.error("包装计划投料数量不能大于库存量");
                return false;
            }

            // 投料
            processPlanInputList.push({
                isPro: this.pageData.useStore,
                stockId: item.id,
                batch: item.batch,
                inputNum: item.inputNumber,
                materialName: item.materialName,
                materialType: item.materialType,
                materialId: item.materialId,
            });
        }

        // 辅料
        this.accSelList.forEach((item) => {
            if (item.inputNum > 0) {
                const findOne = this.accList.find((one) => {
                    return one.id === item.accId;
                });
                if (findOne) {
                    processPlanInputList.push({
                        inputNum: item.inputNum,
                        materialName: findOne.materialName,
                        materialType: findOne.materialType,
                        materialId: findOne.id,
                    });
                }
            }
        });

        const plan = this.planSimulation;
        return [
            {
                isPro: this.pageData.useStore,
                finishTime: this.pageData.finishTime,
                jgfState: this.pageData.jgfState,
                planName: plan.planName,
                name: plan.planName,
                inputNum: plan.xuqiu,
                needNum: plan.xuqiu - total,
                planSerial: plan.planSerial,
                prodNum: plan.preNeed,
                processPlanInputList,
                prodId: plan.prodId,
                prodName:plan.prodName
            },
        ];
    }
}
</script>
<style lang="scss">
.planList-index {
    .planList-top {
        font-size: 16px;
        padding-bottom: 10px;
    }
    .planList-title {
        font-weight: bold;
        font-size: 20px;
    }

    .overview-panel {
        background-color: #fff;
        padding: 10px 10px;
    }
    .overview-title {
        margin-right: 30px;
    }
    .overview-titlebox {
        padding: 10px 0;
    }
}
</style>
